/*
 * BrianClarkeCPE301Design6SERVO.c
 *
 * Created: 5/4/2014 8:23:16 PM
 *  Author: Iguana
 */ 
#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>

int convert(void);
void init();

void init()
{
	DDRC = 0x00;															// Set output
	DDRB = 0xFF;															// Port B enabled
	ADCSRA = 0x87;														// ADC Enable with Clock/128
	ADMUX = 0x40;															// ARef used as VRef and the internal ARef is off with ADLAR = 1
	ICR1=19999;																// Frequency is every 20ms
	TCCR1A = 0;																// Clear TCCR1A
	TCCR1A|=(1<<COM1A1)|(1<<WGM11);						// Enable COM1A1 and WGM11
	TCCR1B = 0;																// Clear TCCR1B
	TCCR1B|=(1<<WGM13)|(1<<WGM12)|(1<<CS11);		// Enable WGM13, WGM12, and CS11
}

int convert(void)
{
	ADCSRA |= (1<<ADSC);											// Start conversion
	while((ADCSRA&(1<<ADIF)) == 0);								// Sit for full conversion
	return (ADC);																// Return value
}

int main(void)
{
	init();																			// Initialize everything
	float angle = 0.0;														// Initialize and clear the angle
	while(1)
	{
		angle = convert();													// Read in ADC value
		angle = (1800.0/1024.0) * angle;								// Scale ADC value by 1.75
		angle = angle + 400;												// Add 400 to match the scaled angle with the duty cycle of servo motor
		OCR1A = angle;
		_delay_ms(55);														// Delay to let the servo alter its angle
		
	}
}
